import React, {Component} from 'react'
import PropTypes from 'react-router/lib/PropTypes'

import {WeaTop, WeaAlertPage, WeaCheckbox } from 'ecCom'

import {Modal, Tooltip, Spin, message, Popover} from 'antd'

import './index.less'

import Cells from "./Cells/"
import WeaDateSwitch from "../wea-date-switch/"
import ConditionDialog from './ConditionDialog';
import CompareDialog from './CompareDialog';
import _get from 'lodash/get';
import {REPORT_TYPE} from './Const';
const confirm = Modal.confirm;

class ReportList extends Component {
    static contextTypes = {
        router: PropTypes.routerShape
    }

    constructor(props) {
        super(props)
        this.query = this.query.bind(this);
        this.addCondition = this.addCondition.bind(this);
        this.checkAll = this.checkAll.bind(this);
        this.checkOne = this.checkOne.bind(this);
        this.compare = this.compare.bind(this);
        this.delete = this.delete.bind(this);
        this.toggleConditionExpand = this.toggleConditionExpand.bind(this);
        this.editTitle = this.editTitle.bind(this);
        this.state = {
            hasCheck: false,
            checkAll: false,
            checkList: [],
            showDate: new Date()
        };
    }

    componentDidMount() {
        this.query();
    }
    
    componentWillReceiveProps(nextProps) {
        if (nextProps.owner.key != this.props.owner.key) {
            this.refs.dateSwitch.setValue(new Date());
            this.query(new Date(), nextProps.owner, nextProps.type);
        } else if (nextProps.type != this.props.type) {
            this.query(this.state.showDate, nextProps.owner, nextProps.type);
        }
        let loading = nextProps.loading;
        if (loading) {
            this.setState({
                checkAll: false,
                hasCheck: false,
                checkList: []
            });
        } else {
            let newLength = _get(nextProps, 'data.tableBody.length', 0);
            if (nextProps.owner.key == REPORT_TYPE.attention && newLength > 0)
                newLength--;
            let oldLength = this.state.checkList.length;
            if (newLength != oldLength) {
                this.setState({
                    checkAll: false,
                    checkList: new Array(newLength)
                });
            }
        }
    }

    renderCell = (cell, key, index, length) => {
        let {cellTitle, cellType, cellValue, oLeftNum, oLeftTitle, oRightNum, oRightTitle, oIndexTitle, oIndexValue} = cell;
        let {showDate} = this.state;
        let Cell = Cells[cellType],
            value = cellValue,
            title = cellTitle;
        switch (cellType) {
            case "total":
                value = [oLeftNum, oRightNum];
                title = [oLeftTitle, oRightTitle];
                break;
            case "index":
                value = oIndexValue;
                title = oIndexTitle;
                break;
            case "report":
            case "normal":
            case "header":
                break;
            default:
                value = ""
                title = ""
                break;
        }
        let className = index == 0 ? "td-first" : ((index == length - 1) ? "td-last" : "");
        return (
            <td key={key} className={className}>
                <Cell {...cell} value={value} title={title} toggleConditionExpand={this.toggleConditionExpand} currentDate={showDate}/>
            </td>
        )
    }

    query(date = new Date(), owner = this.props.owner, type = this.props.type) {
        this.setState({showDate: date});
        let {actions} = this.props;
        switch(owner.key) {
            case REPORT_TYPE.my:
                actions.getReportTable({
                    year: date.getFullYear(),
                    month: date.getMonth() + 1
                });
                break;
            case REPORT_TYPE.attention:
                actions.getAttentionReport({
                    recordType: type ,
                    year: date.getFullYear(),
                    month: date.getMonth() + 1
                });
                break;
            default:
                actions.getTempReportTableInfo({
                    tempId: owner.key,
                    recordType: type,
                    year: date.getFullYear(),
                    month: date.getMonth() + 1
                });
                break;
        }
    }
    
    addCondition() {
        this.refs.conditionDialog.show();
    }
    
    checkAll() {
        // 由于checkList中undefined的值不会被map遍历，所以改为下述写法
        let {checkAll, checkList} = this.state, newList = [];
        checkAll = !checkAll;
        for (let i=0;i<checkList.length;i++)
            newList.push(checkAll);
        this.setState({
            hasCheck: checkAll,
            checkAll: checkAll,
            checkList: newList
        });
    }
    
    checkOne(i) {
        let {checkList} = this.state;
        checkList[i] = !checkList[i];
        let checkAll = checkList.filter((c) => c).length == checkList.length;
        let hasCheck = checkList.some(c=> c);
        this.setState({
            hasCheck: hasCheck,
            checkAll: checkAll,
            checkList:checkList
        });
    }
    
    compare() {
        this.refs.compareDialog.show();
    }
    
    delete() {
        let {actions, data} = this.props,
            {tableBody = []} = data,
            {checkList} = this.state;
        let ids = tableBody.filter((row, i) => checkList[i]).map((row) => row[0] && row[0].conditionId);
        if (ids.length == 0) {
            message.info("请选择要删除的条件");
            return;
        }
        
        let that = this;
        confirm({
            title: "确认要删除这些条件吗？",
            onOk() {
                actions.deleteTempCondition({id: ids.join(',')}, that.query.bind(that, that.state.showDate));
            }
        });
    }
    
    toggleConditionExpand(cell) {
        let {actions, owner, type} = this.props;
        if ("open" in cell) {
            actions.toggleConditionExpand(cell.conditionId);
        } else {
            actions.getTempReportExpandRows({
                tempId: owner.key,
                reportType: type,
                year: this.state.showDate.getFullYear(),
                month: this.state.showDate.getMonth() + 1,
                conditionId: cell.conditionId,
                orgId: cell.oId,
                orgType: cell.oType
            });
        }
    }
    
    render() {
        let {owner, style, data, loading, type} = this.props,
            {tableHeader = [],tableBody = []} = data;
        let {checkAll, checkList, hasCheck,showDate} = this.state;
        let isAttention = owner.key == REPORT_TYPE.attention,
            isCustom = owner.key != REPORT_TYPE.my && !isAttention;
        let title = isCustom ?
            (<Popover
                content={<span className="wea-blog-edit-title" onClick={this.editTitle}><span className="icon-blog-edit" />重命名</span>}
                >
                <span className="cursor-pointer" onClick={this.editTitle}>{owner.title}</span>
            </Popover>)
            : <span style={{cursor: 'default'}}>{owner.title}</span>;
        return (
            <div className="wea-report-content" style={style}>
                {owner.key == REPORT_TYPE.my ? (
                    <div className="wea-rc-foot">
                        <span style={{verticalAlign: "middle"}}>说明：</span>
                        <Cells.report hasText={true} value={"blog_submit_no"}/>
                        <Cells.report hasText={true} value={"blog_submit_ok"}/>
                        <Cells.report hasText={true} value={"mood_unhappy"}/>
                        <Cells.report hasText={true} value={"mood_happy"}/>
                        <Cells.report hasText={true} value={"sign_absent"}/>
                        <Cells.report hasText={true} value={"sing_late"}/>
                        <Cells.report hasText={true} value={"sign_ok"}/>
                        <div><span>"总计"格式为"<span style={{color: "red"}}>未提交总数</span>/提交总数"</span></div>
                    </div>
                ) : (
                    <div className="wea-rc-foot">
                        <span style={{verticalAlign: "middle"}}>说明：</span>
                        {type == 'blog' ?
                            [   <Cells.report hasText={true} value={"blog_submit_no"}/>,
                                <Cells.report hasText={true} value={"blog_submit_ok"}/>
                            ] :
                            [   <Cells.report hasText={true} value={"mood_unhappy"}/>,
                                <Cells.report hasText={true} value={"mood_happy"}/>
                            ]
                        }
                        
                        <div><span>"总计"格式为"<span style={{color: "red"}}>未提交总数</span>/提交总数"</span></div>
                        {isCustom &&
                            <div className="fr button-group">
                                <span className={`icon-coms-contrast-hot ${hasCheck ? '': 'disabled'}`} title="对比" onClick={hasCheck && this.compare}/>
                                <span className="icon-coms-Add-to-hot" title="添加条件" onClick={this.addCondition}/>
                                <span className={`icon-coms-form-delete-hot ${hasCheck ? '':'disabled'}`} title="删除条件" onClick={hasCheck && this.delete}/>
                            </div>
                        }
                        {isAttention &&
                        <div className="fr button-group">
                            <span className={`icon-coms-contrast-hot ${hasCheck ? '': 'disabled'}`} title="对比" onClick={hasCheck && this.compare}/>
                        </div>
                        }
                    </div>
                )}
                <div className="wea-rc-head">
                    <WeaDateSwitch ref="dateSwitch" defaultValue={new Date()} onChange={this.query}
                                   title={title} style={{fontSize: "14px"}}/>
                </div>
                {loading ? <div className="align-center mt10"><Spin size="large"/></div> :
                    (tableHeader.length == 0 || tableBody.length == 0) ?
                    <WeaAlertPage icon="icon-blog-blank">
                        <div>{isAttention ? '当前没有关注的人' : '暂无数据'}</div>
                    </WeaAlertPage> :
                    <table className="wea-rc-table">
                        <tbody>
                            <tr>
                                {(isCustom || isAttention)&& <td><WeaCheckbox value={checkAll} onChange={this.checkAll}/></td>}
                                {tableHeader.map((td, i) => this.renderCell(td, owner.key + "header" + i, i, tableHeader.length))}
                            </tr>
                            {tableBody.length > 0 && tableBody.map((rows, i) =>{
                                // 是否有复选框列但没有复选框。关注报表最后的总计列是这个情况。
                                let noCheckBox = isAttention && i == tableBody.length - 1;
                                let arr = [];
                                arr.push(
                                    <tr key={`tr${i}`}>
                                        {(isCustom || isAttention) && <td>{noCheckBox || <WeaCheckbox value={!!checkList[i]} onChange={this.checkOne.bind(this, i)}/>}</td>}
                                        {rows.map((td, j)=> this.renderCell(td, owner.key + "cell" + i + "_" + j, j, tableHeader.length))}
                                    </tr>
                                );
                                if (rows[0].loading) {
                                    arr.push(<tr key={`sub_loading${i}`}><td colSpan={tableHeader.length + 1}><Spin tip="正在读取数据..."></Spin></td></tr>);
                                }
                                if (rows[0].open) {
                                    let subList = _get(rows,"[0].subList.allRows", []);
                                    arr = arr.concat(subList.map((subRow, k) =>
                                        <tr key={`sub${k}`}>
                                            <td />
                                            {subRow.map((td, j)=> this.renderCell(td, owner.key + "sub" + k + "_" + j, j, tableHeader.length))}
                                        </tr>
                                    ));
                                }
                                
                                return arr;
                            })}
                        </tbody>
                    </table>
                }
                <ConditionDialog ref="conditionDialog" reportId={owner.key} saveCallback={this.query.bind(this, showDate || new Date())}/>
                <CompareDialog ref="compareDialog" reportId={owner.key} title={owner.title} tableBody={tableBody} cols={checkList} currentDate={showDate} type={type}/>
            </div>
        )
    }
    
    editTitle() {
        let {editReport, owner} = this.props;
        editReport && editReport(owner);
    }
}

/**
 * 属性说明：
 *  owner.key标识报表类型
 *      myReport:我的报表。需要actions.getReportTable实现查询方法,不使用type属性。
 *      attentionReport:关注报表。需要actions.getAttentionReport实现查询方法
 *      其它：自定义报表。会拥有添加、删除条件功能。需要actions.getTempReportTableInfo实现查询方法，actions.deleteTempCondition实现删除方法
 *  owner.title标识报表标题。
 *  style:自定义样式。
 *  loading: 是否加载中
 *  type: 类型.blog:微博，mood:心情
 *  data: 展示的数据。tableHeader为头部，tableBody为内容部分。
 *
 */
ReportList.propTypes = {
    owner: React.PropTypes.object.isRequired,
    style: React.PropTypes.object,
    data: React.PropTypes.object,
    loading: React.PropTypes.bool,
    type: React.PropTypes.string,
    actions: React.PropTypes.object.isRequired
};

export default ReportList

